package com.wenwo.logging.aspect;


import com.alibaba.fastjson.JSON;
import com.wenwo.logging.dto.MethodInvokeInfoDTO;
import com.wenwo.logging.service.LogService;
import com.wenwo.logging.util.DtoBuilder;
import com.wenwo.logging.util.RequestHolder;
import com.wenwo.logging.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author : ZY
 * @program: operate-backend
 * @className: LogAspect.java
 * @description:
 * @create: 2020年08月02日 14:10
 **/
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Resource
    private LogService logService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    ThreadLocal<Object> methodReturn = new ThreadLocal<>();

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.wenwo.logging.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 返回前将方法的返回值按需放到ThreadLocal中
     * 在执行到Around时从ThreadLocal中取出联合请求参数一起进行日志记录(或者埋点)
     *
     * @param result 方法返回结果
     */
    @AfterReturning(value = "logPointcut()", returning = "result")
    public void logAfterReturn(Object result) {
        // 获取方法的返回值，放到ThreadLocal中
        methodReturn.set(result);
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        currentTime.set(System.currentTimeMillis());
        Object o = joinPoint.proceed();
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        // TODO 这里根据连接点和request来组装需要的对象
        MethodInvokeInfoDTO dto = DtoBuilder.buildMethodInvokeInfoDTO(joinPoint, request, currentTime.get(), "INFO");
        currentTime.remove();

        // 从ThreadLocal拿出方法返回值
        Map<?, ?> result = JSON.parseObject(JSON.toJSONString(methodReturn.get()), Map.class);
        methodReturn.remove();
        Map<?, ?> data = JSON.parseObject(JSON.toJSONString(result.get("data")), Map.class);
        dto.setUserId((String) data.get("userId"));
        dto.setUsername((String) data.get("username"));
        // 将组装好的dto信息通过http接口异步请求到上报信息系统接口处理(或者发送到消息系统)
        logService.logMethodInvokeInfo(dto);
        return o;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        MethodInvokeInfoDTO dto = DtoBuilder.buildMethodInvokeInfoDTO(joinPoint, request, currentTime.get(), "ERROR");
        currentTime.remove();
        dto.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        // 将组装好的dto信息通过http接口异步请求到上报信息系统接口处理(或者发送到消息系统)
        logService.logMethodInvokeInfo(dto);
    }

}
